package com.example.accessibilityhelper.util;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.graphics.Path;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.RequiresApi;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


public class AccessibilityUtils {

    private static final String TAG = "SCRM_ACC_UTILS";



    @SuppressLint("NewApi")
    public static void clickByGesture(AccessibilityService service, AccessibilityNodeInfo node) {
        Log.d(TAG, "Perform click by gesture.");
        final CountDownLatch latch = new CountDownLatch(1);
        Rect rect = new Rect();
        node.getBoundsInScreen(rect);
        Path path = new Path();
        path.moveTo(rect.centerX(), rect.centerY()); //TODO 随机位置，随机点击时间
        path.lineTo(rect.centerX(), rect.centerY());
        GestureDescription.Builder builder = new GestureDescription.Builder();

        GestureDescription.StrokeDescription stroke = new GestureDescription.StrokeDescription(path, 0, 100);
        builder.addStroke(stroke);
        GestureDescription gesture = builder.build();
        final boolean[] resultHolder = new boolean[1];

        service.dispatchGesture(gesture, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.d(TAG, "onCompleted: 完成..........");
                resultHolder[0] = true;
                latch.countDown();
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.d(TAG, "onCompleted: 取消..........");
                resultHolder[0] = false;
                latch.countDown();
            }
        }, null);
        try {
            latch.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Log.e(TAG, "Wait gesture complete interrupted.", e);
        }
    }

}
